package com.jeesite.modules.wx.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.zxing.WriterException;
import com.jeesite.common.lang.DateUtils;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.modules.common.BusinessUtils;
import com.jeesite.modules.common.InviteDoImg;
import com.jeesite.modules.common.QRCodeUtils;
import com.jeesite.modules.common.QiniuUtils;
import com.jeesite.modules.common.img.ChangeImage;
import com.jeesite.modules.common.refun.CollectionUtil;
import com.jeesite.modules.common.refun.StringUtil;
import com.jeesite.modules.config.redis.RedisHandle;
import com.jeesite.modules.wx.entity.*;
import com.jeesite.modules.wx.service.*;
import com.qiniu.common.QiniuException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;
import java.util.List;

@RestController
@Slf4j
public class ApiController {

    @Autowired
    private WxActivityThemeService wxActivityThemeService;

    @Autowired
    private WxActivityService wxActivityService;

    @Autowired
    private WxBusinessService wxBusinessService;

    @Autowired
    private WxActivityDisUserService wxActivityDisUserService;

    @Autowired
    private WxUserService wxUserService;

    @Autowired
    private WxUserDisValueRecordService wxUserDisValueRecordService;

    @Autowired
    private WxBusinessApplyService wxBusinessApplyService;

    @Autowired
    private WxUserOrderService wxUserOrderService;

    @Autowired
    private WxUserActivityAfterService wxUserActivityAfterService;

    @Autowired
    private WxUserInviteImgService wxUserInviteImgService;

    @Autowired
    private RedisHandle redisHandle;

    @Autowired
    private WxBusinessGroupService wxBusinessGroupService;


    /**
     * 获取活动页面的主题
     * @return
     */
    @RequestMapping("/getTheme")
    public String getTheme(){
        List<WxActivityTheme> wxActivityThemeList = wxActivityThemeService.findList(new WxActivityTheme());

        return "";

    }

    /**
     * 首页海报信息接口
     * @return
     */
    @RequestMapping("/getIndex")
    public JSONObject getIndex(String activityId ,String userOpenId){

        WxActivity getActivity = wxActivityService.get(activityId);
        //真实参与活动人数
        Long realNum = getActivity.getRealNum();
        if(null == realNum){
            realNum = 0L;
        }

        //更新用户涉及的活动
        try {
            WxUser wxUser = wxUserService.findByOpenId(userOpenId);
            //查询涉及的活动ids
            String attendActivityIds = wxUser.getAttendActivityIds();
            if(StringUtil.isNotEmpty(attendActivityIds)){
                //用户涉及活动不包含当前活动
                if(!attendActivityIds.contains(activityId)){
                    wxUser.setAttendActivityIds(wxUser.getAttendActivityIds()+","+activityId);
                    wxUserService.update(wxUser);
                    //活动的真实人数++
                    getActivity.setRealNum(realNum+1);
                    //保存
                    try {
                        wxActivityService.save(getActivity);
                    }catch (Exception e){
                        e.printStackTrace();
                        log.error("参加过其他红多，保存活动真实参与人数错误={}",e.getMessage());
                    }

                }else{
                    log.info("用户已经包含在该活动中");
                }
            }else{
                //用户没有涉及过活动
                wxUser.setAttendActivityIds(activityId+",");
                wxUserService.update(wxUser);
                getActivity.setRealNum(realNum+1);
                //保存
                try {
                    wxActivityService.save(getActivity);
                }catch (Exception e){
                    e.printStackTrace();
                    log.error("从未参加过活动，保存活动真实参与人数错误={}",e.getMessage());
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            log.error("更新用户涉及活动错误={}",e.getMessage());
        }

        //活动开始时间
        Date beginTime = getActivity.getBeginTime();
        //活动结束时间
        Date endTime = getActivity.getEndTime();
        //活动的价格
        String price = getActivity.getPrice();
        //活动的规则
        String rule = getActivity.getRule().replace("\n\n","<br/>").replace("\n","");
        //活动标题
        String title = getActivity.getTitle();
        //主题
        Integer theme = getActivity.getTheme();
        //banner
        String bannerPic = getActivity.getBannerPic();
        //用于打电话联系
        String phone = getActivity.getPhone();
        //入群二维码
        String groupPic = getActivity.getGroupPic();
        //bgm
        String bgm = getActivity.getBgm();

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("title",title);
        jsonObject.put("rule",rule);
        jsonObject.put("price",price);
        jsonObject.put("endTime",endTime);
        jsonObject.put("beginTime",beginTime);
        jsonObject.put("endTime",endTime);
        jsonObject.put("num",realNum);
        jsonObject.put("theme",theme);
        jsonObject.put("bannerPic",bannerPic);
        jsonObject.put("phone",phone);
        jsonObject.put("groupPic",groupPic);
        jsonObject.put("bgm",bgm);
        if(new Date().after(endTime)) {
            jsonObject.put("overTime",1);
        }else{
            jsonObject.put("overTime",0);
        }

            //检查自己是否购买了
        WxUserDisValueRecord wxUserDisValueRecord = new WxUserDisValueRecord();
        wxUserDisValueRecord.setBuyActivityId(Long.valueOf(activityId));
        wxUserDisValueRecord.setBuyUserOpenId(userOpenId);
        wxUserDisValueRecord.setBuyFlag(1);
        List<WxUserDisValueRecord> wxUserDisValueRecordList = wxUserDisValueRecordService.findList(wxUserDisValueRecord);
        if(CollectionUtil.isNotEmpty(wxUserDisValueRecordList)){
            jsonObject.put("isBuyActivity",1);
        }else{
            jsonObject.put("isBuyActivity",0);
        }


        return jsonObject;
    }

    /**
     * 查询自己赚的钱
     * @param userOpenId
     * @param activityId
     */
    @RequestMapping("/selDisBuyList")
    @ResponseBody
    public JSONObject selDisBuyList(String userOpenId,String activityId){

        WxUser wxUser = wxUserService.findByOpenId(userOpenId);

        JSONObject jsonObject = new JSONObject();

        JSONArray jsonArray = new JSONArray();
        WxUserDisValueRecord wxUserDisValueRecord = new WxUserDisValueRecord();
        wxUserDisValueRecord.setBuyActivityId(Long.valueOf(activityId));
        wxUserDisValueRecord.setUserId(Long.valueOf(wxUser.getId()));
        wxUserDisValueRecord.setBuyFlag(1);
        List<WxUserDisValueRecord> wxUserDisValueRecordList = wxUserDisValueRecordService.findList(wxUserDisValueRecord);
        for(WxUserDisValueRecord temp: wxUserDisValueRecordList){

            JSONObject j = new JSONObject();
            Long buyUserId = temp.getBuyUserId();
            WxUser buyWxUser = wxUserService.findByOpenId(temp.getBuyUserOpenId());

            BigDecimal disMoneyValue = temp.getDisMoneyValue();

            //购买用户的昵称
            j.put("buyNickName",buyWxUser.getNickName());
            //购买用户的头像
            j.put("buyUserHeadImg",buyWxUser.getHeadImg());
            //购买用湖的金额
            j.put("buyPrice",temp.getBuyPrice().toString());
            //返佣金
            j.put("disMoneyValue",disMoneyValue.toString());
            //时间
            j.put("buyTime", DateUtils.formatDate(temp.getUpdateDate()));

            jsonArray.add(j);

        }
        jsonObject.put("data",jsonArray);

        return jsonObject;
    }

    /**
     * 获得商家 显示商家头像和名称(最新使用)
     * 获得主推商家，显示会员卡和商家头像商家电话商家地址商家名称
     *
     * 这里的缓存，修改涉及到，商家的信息修改影响详细信息的展示，商家分组的修改影响需要删除的商家
     * @return
     */
    @RequestMapping("/getBusiness")
    public JSONObject getBusinessNew(String activityId){
        //直接获取缓存
        JSONObject cacheResult = (JSONObject) redisHandle.get("businessList:"+activityId);
        if(null != cacheResult){
            return cacheResult;
        }
        WxActivity wxActivity = wxActivityService.get(activityId);
        //获得活动配置分组商家
        Long groupId = wxActivity.getBusinessGroupId();
        log.info("groupId={}",groupId);
        JSONObject result = wxBusinessGroupService.getSort(groupId);
        //加入缓存,5小时
        redisHandle.set("businessList:"+activityId,result,60*60*5L);
        return result;
    }

//    /**
//     * 获得商家 显示商家头像和名称
//     * 获得主推商家，显示会员卡和商家头像商家电话商家地址商家名称
//     * @return
//     */
//    @RequestMapping("/getBusiness")
//    public JSONObject getBusiness(String activityId){
//        //直接获取缓存
//        JSONObject cacheResult = (JSONObject) redisHandle.get("businessList:"+activityId);
//        if(null != cacheResult){
//            return cacheResult;
//        }
//
//        JSONArray jsonArrayBusiness = new JSONArray();
//        //单独一行的数据
//        JSONArray nextJsonArrayBusiness = new JSONArray();
//
//
//        JSONArray jsonArrayMainBusiness = new JSONArray();
//
//        WxActivity wxActivity = wxActivityService.get(activityId);
//
//        //商家排名提前
//        String[] firstBusinessName = new String[]{""};
//        int maxlen = 0;
//        //东营免单
//        if(wxActivity.getId().equals("1062961764050448384")){
//            firstBusinessName = new String[]{"柏年超群", "铂尔口腔", "指尖芭蕾美业", "花儿胡同音乐酒馆", "老尹驴肉",
//                    "K1儿童乐园", "潮汕牛肉火锅", "威廉英语教育学校", "妙医堂中医门诊部", "车娘家"};
//            maxlen = 4;
//        }else if(wxActivity.getId().equals("1063743970693001216")){
//            //枣庄免单
//            firstBusinessName = new String[]{"新恒志服饰","咔多堡汉堡","苏菲玛索婚纱摄影","银河珠宝城",
//                    "布衣侯粥道馆（枣庄旗舰店）","鲁国人家酒店","新郎·希努尔男装","报喜鸟男装"};
//            maxlen = 3;
//        }else{
//            //获得活动配置的商家分组
//            Long groupId = wxActivity.getBusinessGroupId();
//            if(null != groupId){
//                wxBusinessGroupService.getSort(groupId,maxlen,firstBusinessName);
//            }
//
//        }
//
//
//        int flen = firstBusinessName.length;
//        for(int i= 0;i<flen;i++){
//            WxBusiness wxBusiness = new WxBusiness();
//            wxBusiness.setName(firstBusinessName[i].trim());
//            List<WxBusiness> wxBusinessList = wxBusinessService.findList(wxBusiness);
//            if(CollectionUtil.isNotEmpty(wxBusinessList)){
//                WxBusiness temp = wxBusinessList.get(0);
//                JSONObject jsonObject = new JSONObject();
//                jsonObject.put("businessId",temp.getId());
//                jsonObject.put("businessName",temp.getName());
//                jsonObject.put("businessPic",temp.getPic());
//                if(i > maxlen){
//                    //需要添加到下一行的数据array中
//                    nextJsonArrayBusiness.add(jsonObject);
//                }else{
//                    jsonArrayBusiness.add(jsonObject);
//                }
//            }
//        }
//
//        //获取商家 ，分割
//        String business = wxActivity.getBusiness();
//        //获取主推商家
//        String mainBusiness = wxActivity.getBusinessApply();
//
//        if(StringUtils.isNotEmpty(business)){
//            String[] businessArray = business.split(",");
//            int len = businessArray.length;
//            //算出折行
//            int nextLen = len + nextJsonArrayBusiness.size();
//            nextLen = (nextLen / 2) - 1 ;
//
//            for(int i = 0;i<len;i++){
//
//                String businessId = businessArray[i];
//                WxBusiness wxBusiness = wxBusinessService.get(businessId);
//                if(null != wxBusiness){
//                    String businessName = wxBusiness.getName().trim();
//
//                    int check = Arrays.binarySearch(firstBusinessName,businessName);
//                    if(check >= 0){
//                        continue;
//                    }
//
//                    JSONObject jsonObject = new JSONObject();
//                    jsonObject.put("businessId",businessId);
//                    jsonObject.put("businessName",businessName);
//                    jsonObject.put("businessPic",wxBusiness.getPic());
//
//                    if(jsonArrayBusiness.contains(jsonObject)){
//                        continue;
//                    }
//                    //或者这行的存在也去除
//                    if(nextJsonArrayBusiness.contains(jsonObject)){
//                        continue;
//                    }
//
//                    jsonArrayBusiness.add(jsonObject);
//                }
//            }
//
//            log.info("len={}",jsonArrayBusiness.size());
//
//            jsonArrayBusiness.addAll(nextLen,nextJsonArrayBusiness);
//            log.info("添加折行后len={}",jsonArrayBusiness.size());
//        }
//
//        //会员卡
//        if(StringUtils.isNotEmpty(mainBusiness)){
//
//            String[] mainBusinessArray = mainBusiness.split(",");
//            int len = mainBusinessArray.length;
//
//            for(int i=0;i<len;i++){
//
//                String id = mainBusinessArray[i];
//                WxBusiness wxBusiness = wxBusinessService.get(id);
//                if(null != wxBusiness){
//
//                    JSONObject jsonObject = new JSONObject();
//                    jsonObject.put("mainBusinessId",id);
//                    jsonObject.put("mainBusinessPic",wxBusiness.getPic());
//                    jsonObject.put("mainBusinessName",wxBusiness.getName());
//                    jsonObject.put("mainBusinessAddress",wxBusiness.getAddress());
//                    jsonObject.put("mainBusinessVipCardImg",wxBusiness.getVipCardImg());
//                    jsonObject.put("mainBusinessPhone",wxBusiness.getPhone());
//
//                    jsonArrayMainBusiness.add(jsonObject);
//
//
//                }
//            }
//        }
//
//        JSONObject result = new JSONObject();
//        result.put("business",jsonArrayBusiness);
//        result.put("mainBusiness",jsonArrayMainBusiness);
//
//        //加入缓存
//        redisHandle.set("businessList:"+activityId,result);
//        return result;
//    }

    /**
     * 获取商家配置的分享信息
     * @param activityId
     * @return
     */
    @RequestMapping("/getShareInfo")
    public JSONObject getShareInfo(String activityId,String userOpenId){
        WxUser wxUser = wxUserService.findByOpenId(userOpenId);

        if(StringUtils.isEmpty(activityId)){
            log.error("获取商家分享信息参数activityId为空={}",activityId);
        }

        WxActivity activity =  wxActivityService.get(activityId);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("shareTitle",activity.getShareTitle());
        jsonObject.put("sharePic",activity.getSharePic());
        jsonObject.put("shareContent",wxUser.getNickName()+" "+activity.getShareContent());
        //获取分享的链接


        return jsonObject;
    }



    /**
     * 有钱大家赚,目前使用接口
     * @param activityId
     * @return
     */
    @RequestMapping("/getActivityDisMoneyList")
    public JSONArray getDisMoneyByActivityId(String activityId){
        JSONArray cacheReuslt = (JSONArray) redisHandle.get("moneyList:"+activityId);
        if(null != cacheReuslt){
            return cacheReuslt;
        }

        //首先查询wx_user_dis_value中所有该活动下的用户
        WxActivityDisUser wxActivityDisUser = new WxActivityDisUser();
        wxActivityDisUser.setActivityId(activityId);
        List<WxActivityDisUser>  wxActivityDisUserList = wxActivityDisUserService.findList(wxActivityDisUser);

        List<WxUser> haveDis = new LinkedList<>();
        if(CollectionUtils.isNotEmpty(wxActivityDisUserList)){
            for(WxActivityDisUser temp : wxActivityDisUserList){

                Long userId = temp.getUserId();
                //得到这个活动中被返佣的用户，需要查询他们的总金额的次数
                WxUser wxUser = wxUserService.get(userId.toString());
                haveDis.add(wxUser);

            }
        }

        log.info("");

        //遍历用户查询用户总
        for(WxUser inviteUser:haveDis){

            WxUserDisValueRecord wxUserDisValueRecord = new WxUserDisValueRecord();
            wxUserDisValueRecord.setBuyActivityId(Long.valueOf(activityId));
            wxUserDisValueRecord.setUserOpenId(inviteUser.getWxOpenId());
            wxUserDisValueRecord.setBuyFlag(1);
            List<WxUserDisValueRecord> wxUserDisValueRecordList = wxUserDisValueRecordService.findList(wxUserDisValueRecord);
            BigDecimal disAmount = BigDecimal.ZERO;
            Integer disTimes = 0;
            if(CollectionUtil.isNotEmpty(wxUserDisValueRecordList)){

                for(WxUserDisValueRecord moneyList:wxUserDisValueRecordList){
                    if(null != moneyList.getDisMoneyValue()){
                        disAmount = disAmount.add(moneyList.getDisMoneyValue());
                        ++disTimes;
                    }
                }
            }
            inviteUser.setDisMoneyValue(disAmount.setScale(0).toString());
            inviteUser.setDisInviteNum(disTimes.toString());
        }

        //排序
        Collections.sort(haveDis, new Comparator<WxUser>() {
            @Override
            public int compare(WxUser o1, WxUser o2) {
                BigDecimal disAmount1 = new BigDecimal(o1.getDisMoneyValue());
                BigDecimal disAmount2 = new BigDecimal(o2.getDisMoneyValue());
                return disAmount2.compareTo(disAmount1);
            }
        });

        //太长了截取
        Integer len = haveDis.size();
        if(null != len && len > 60){
            haveDis = haveDis.subList(0,59);
        }

        //最后加工数据
        JSONArray jsonArray = new JSONArray();
        for(WxUser inviteUser:haveDis){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("userHeadImg",inviteUser.getHeadImg());
            jsonObject.put("userName",inviteUser.getNickName());
            //总反佣金
            jsonObject.put("disMoney",inviteUser.getDisMoneyValue());
            //总次数
            jsonObject.put("disNum",inviteUser.getDisInviteNum());
            //userId
            jsonObject.put("userId",inviteUser.getId());
            jsonArray.add(jsonObject);
        }

        //加入缓存,5个小时
        redisHandle.set("moneyList:"+activityId,jsonArray,60*60*5L);
        return jsonArray;
    }


    /**
     * 弹幕数据
     * @param activityId
     * @return
     */
    @RequestMapping(value = "danmu")
    @ResponseBody
    public JSONObject danmu(String activityId){
        JSONObject result = new JSONObject();

        JSONArray topJsonArray = new JSONArray();
        JSONArray leftJsonArray = new JSONArray();
//        {
//            msg: '恭喜杜升蔚获得100元',
//                    top: 2,
//                left: left - 0,
//                headImg:'https://image.lanstech.cn/bc765ac6-6d96-4ce8-9af6-2b5cbb88c219.jpg'
//        },
//        {
//            msg: '恭喜李静获得100元',
//                    top: 4,
//                left: left - 3,
//                headImg:'https://image.lanstech.cn/e3751731-2899-4a63-bc63-027438225c30.jpg'
//        }

        WxActivityDisUser wxActivityDisUser = new WxActivityDisUser();
        wxActivityDisUser.setActivityId(activityId);
        List<WxActivityDisUser>  wxActivityDisUserList = wxActivityDisUserService.findList(wxActivityDisUser);
        if(CollectionUtil.isNotEmpty(wxActivityDisUserList)){
            int i = 0;
            for(WxActivityDisUser t : wxActivityDisUserList){
                if(i > 4){
                    break;
                }

                //        msg: '恭喜刘威购买成功',
//                top: 0,
//                left: 0.1,
//                headImg:'https://image.lanstech.cn/679e0205-1d63-4656-a354-ec89200331ba.jpg'
//    },
//    {
//        msg: '恭喜牛倩倩购买成功',
//                top: 1.5,
//            left: 0.1,
//            headImg:'https://image.lanstech.cn/bf56a7df-b05e-4879-957a-a41da597ca8a.jpg'
//    },
//    {
//        msg: '恭喜于鹏飞购买成功',
//                top: 3,
//            left: 0.1,
//            headImg:'https://image.lanstech.cn/d4d3ccd8-d7a7-4cdf-9add-9af6809fd872.jpg'
//    }
//        ]
                Long userId = t.getUserId();
                WxUser wxUser = wxUserService.get(userId.toString());
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("msg","恭喜"+wxUser.getNickName()+"获得100元");
                if(i == 0){
                    jsonObject.put("top",2);
                    jsonObject.put("left","0");

                }else if(i ==1){
                    jsonObject.put("top",4);
                    jsonObject.put("left","10");

                }else if(i == 2){
                    jsonObject.put("top",0);
                    jsonObject.put("left","0.1");
                    jsonObject.put("msg","恭喜"+wxUser.getNickName()+"购买成功");

                }else if(i == 3){
                    jsonObject.put("top",1.5);
                    jsonObject.put("left","0.1");
                    jsonObject.put("msg","恭喜"+wxUser.getNickName()+"购买成功");

                }else if(i == 4){
                    jsonObject.put("top",3);
                    jsonObject.put("left","0.1");
                    jsonObject.put("msg","恭喜"+wxUser.getNickName()+"购买成功");

                }
                jsonObject.put("headImg",wxUser.getHeadImg());

                if(i > 1){
                    leftJsonArray.add(jsonObject);
                }else{
                    topJsonArray.add(jsonObject);
                }

                ++i;
            }

        }

        result.put("top",topJsonArray);
        result.put("left",leftJsonArray);

        return result;
    }


    /**
     * 有钱大家赚
     * @param activityId
     * @return
     */
    @RequestMapping("/getActivityDisMoneyListOld")
    public JSONArray getActivityDisMoneyListOld(String activityId){

        //首先查询wx_user_dis_value中所有该活动下的用户
        WxActivityDisUser wxActivityDisUser = new WxActivityDisUser();
        wxActivityDisUser.setActivityId(activityId);

        List<WxActivityDisUser>  wxActivityDisUserList = wxActivityDisUserService.findList(wxActivityDisUser);
        List<WxUser> haveDis = new LinkedList<>();
        if(CollectionUtils.isNotEmpty(wxActivityDisUserList)){


            for(WxActivityDisUser temp : wxActivityDisUserList){

                Long userId = temp.getUserId();
                //得到这个活动中被返佣的用户，需要查询他们的总金额的次数
                WxUser wxUser = wxUserService.get(userId.toString());
                haveDis.add(wxUser);

            }
        }

        //对拥有该活动下返佣的用户进行返佣金额的排序
        Collections.sort(haveDis, new Comparator<WxUser>() {
            @Override
            public int compare(WxUser o1, WxUser o2) {
                return o2.getDisMoneyValue().compareTo(o1.getDisMoneyValue());
            }
        });

        //只截取前5位

        int len = haveDis.size();
        if(len > 5){
            haveDis = haveDis.subList(0,5);
        }

        JSONArray jsonArray = new JSONArray();
        for(WxUser wxUser : haveDis){

            JSONObject jsonObject = new JSONObject();

            jsonObject.put("userHeadImg",wxUser.getHeadImg());
            jsonObject.put("userName",wxUser.getNickName());
            //总反佣金
            jsonObject.put("disMoney",wxUser.getDisMoneyValue());
            //查询该用户在这个活动中总共拉取了多少用户
            WxUserDisValueRecord wxUserDisValueRecord = new WxUserDisValueRecord();
            wxUserDisValueRecord.setUserId(Long.valueOf(wxUser.getId()));

            List<WxUserDisValueRecord> wxUserDisValueRecordList = wxUserDisValueRecordService.findList(wxUserDisValueRecord);
            if(CollectionUtils.isNotEmpty(wxUserDisValueRecordList)){
                jsonObject.put("disNum",wxUserDisValueRecordList.size());
            }else{
                jsonObject.put("disNum",0);
            }

            jsonArray.add(jsonObject);
        }

        return jsonArray;
    }

    /**
     * 申请加盟
     * @param businessName
     * @param people
     * @param phone
     * @param address
     * @return
     */
    @RequestMapping("/insertBusinessApply")
    public Integer insertBusinessApply(@RequestParam("businessName") String businessName,
                                       @RequestParam("people") String people,
                                       @RequestParam("phone") String phone,
                                       @RequestParam("address") String address){

        try {
            WxBusinessApply wxBusinessApply = new WxBusinessApply();
            wxBusinessApply.setName(businessName);
            wxBusinessApply.setPhone(phone);
            wxBusinessApply.setPeople(people);
            wxBusinessApply.setAddress(address);

            wxBusinessApplyService.insert(wxBusinessApply);
        }catch (Exception e){
            return 0;
        }


        return 1;
    }

    @RequestMapping("/getBusinessInfo")
    public JSONObject getBusinessInfo(String businessId) {

        JSONObject jsonObject = new JSONObject();

        WxBusiness wxBusiness = wxBusinessService.get(businessId);
        if(null != wxBusiness){

            jsonObject.put("name",wxBusiness.getName());
            jsonObject.put("pic",wxBusiness.getPic());
            jsonObject.put("vipCardImg",wxBusiness.getVipCardImg());
            jsonObject.put("phone",wxBusiness.getPhone());
            jsonObject.put("phoneRes",wxBusiness.getPhoneRes());
            jsonObject.put("gongzhonghao",wxBusiness.getGongzonghao());
            jsonObject.put("address",wxBusiness.getAddress());
            jsonObject.put("content",wxBusiness.getContent());
            jsonObject.put("radio",wxBusiness.getRadio());
            jsonObject.put("videoImg",wxBusiness.getVideoImg());
            //经纬度
            jsonObject.put("left",wxBusiness.getWeizhiLeft());
            jsonObject.put("right",wxBusiness.getWeizhiRight());
            jsonObject.put("weizhi",wxBusiness.getWeizhiLeft()+","+wxBusiness.getWeizhiRight());

            JSONArray jsonArray = new JSONArray();
            //获取商家详情图片
            String detailImgs = wxBusiness.getDetailImg();
            if(StringUtil.isNotEmpty(detailImgs)){
                String[] detailImgArray = detailImgs.split(",");
                int len = detailImgArray.length;
                for(int i = 0;i<len;i++){
                    String detailImg = detailImgArray[i];
                    if(StringUtil.isEmpty(detailImg)){
                        continue;
                    }
                    JSONObject t = new JSONObject();
                    t.put("detailImg",detailImg);
                    jsonArray.add(t);
                }
            }
            jsonObject.put("detailImgArray",jsonArray);
        }

        return jsonObject;
    }

    /**
     * 邀请好友
     * @param activityId
     * @param userOpenId
     * @return
     */
    @RequestMapping("/invite")
    public JSONObject invite(String activityId,String userOpenId) throws Exception {
        JSONObject jsonObject = new JSONObject();

        WxUser wxUser = wxUserService.findByOpenId(userOpenId);

            jsonObject.put("userName",wxUser.getNickName());
            jsonObject.put("headImg",wxUser.getHeadImg());
            jsonObject.put("isSuccess",true);

            //活动的自定义邀请好友背景
            WxActivity wxActivity = wxActivityService.get(activityId);
            jsonObject.put("inviteBannerPicSource",wxActivity.getInviteBannerPic());
            jsonObject.put("inviteBannerPic",wxActivity.getInviteBannerPic());
            log.info("邀请好友wxActivity={}",wxActivity);
            log.info("邀请好友getQrIndex={}",wxActivity.getQrIndex());
            log.info("邀请好友getHeadImgIndex={}",wxActivity.getHeadImgIndex());
            log.info("邀请好友getUserNameIndex={}",wxActivity.getUserNameIndex());


            log.info("邀请好友getUserNameIndex={}",wxActivity.getQrIndex().contains(","));
            log.info("邀请好友getUserNameIndex={}",wxActivity.getHeadImgIndex().contains(","));
            log.info("邀请好友getUserNameIndex={}",wxActivity.getUserNameIndex().contains(","));

            //获得弄好的位置
            if(!wxActivity.getQrIndex().contains(",") || !wxActivity.getHeadImgIndex().contains(",")
            || !wxActivity.getUserNameIndex().contains(",")){
                log.error("生成邀请好友海报错误，未配置自定义坐标");
                jsonObject.put("isSuccess",false);
                return jsonObject;
            }
            String[] qrIndex = wxActivity.getQrIndex().split(",");
            String[] headImgIndex = wxActivity.getHeadImgIndex().split(",");
            String[] userNameIndex = wxActivity.getUserNameIndex().split(",");

            log.info("qrIndex={}",Arrays.toString(qrIndex));
            log.info("headImgIndex={}",Arrays.toString(headImgIndex));
            log.info("userNameIndex={}",Arrays.toString(userNameIndex));



            //查询用户是否购买过活动
            WxUserDisValueRecord wxUserDisValueRecord = new WxUserDisValueRecord();
            wxUserDisValueRecord.setBuyActivityId(Long.valueOf(activityId));
            wxUserDisValueRecord.setBuyUserOpenId(userOpenId);
            wxUserDisValueRecord.setBuyFlag(1);
            List<WxUserDisValueRecord> wxUserDisValueRecordList = wxUserDisValueRecordService.findList(wxUserDisValueRecord);
            if(CollectionUtil.isNotEmpty(wxUserDisValueRecordList)){
                jsonObject.put("isPay",0);
            }else{
                jsonObject.put("isPay",1);
            }

            //二维码
            String url = BusinessUtils.getWxIndexFrontServer()+"?activityId="+activityId+"&inviteUserOpenId="+userOpenId;
            String qrCodeUrl = "";
            try {
                qrCodeUrl = QRCodeUtils.encode(url);
                jsonObject.put("qrCodeUrl",qrCodeUrl);

            } catch (WriterException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }


            //查询用户是否生成过活动的邀请合成图片
            Integer flag = wxActivity.getRefreshInviteImg();

            WxUserInviteImg wxUserInviteImg = new WxUserInviteImg();
            wxUserInviteImg.setUserOpenId(userOpenId);
            wxUserInviteImg.setActivityId(activityId);
            List<WxUserInviteImg> wxUserInviteImgList = wxUserInviteImgService.findList(wxUserInviteImg);
            if(CollectionUtils.isNotEmpty(wxUserInviteImgList) && (null != flag && flag != 1) ){
                log.info("查询用户是否生成过活动的邀请合成图片={}",wxUserInviteImgList);
                jsonObject.put("inviteBannerPic",wxUserInviteImgList.get(0).getInviteImg());

            }else{
                //加载二维码图片
                String qrImg = InviteDoImg.createLocalFile(qrCodeUrl,userOpenId+"|qr.jpg");

                //获取活动图,这个在上传我的邀请页面时候就保存到了
                String activityImg = InviteDoImg.createLocalFile(wxActivity.getInviteBannerPic(),activityId+".jpg");

                //获取头像图片
                String headImg = InviteDoImg.createLocalFile(wxUser.getHeadImg(),userOpenId+"|head.jpg");
                //缩小头像图片
                ChangeImage.resizePNG(headImg, headImg, 60, 60,false);
//                ChangeImage.resizePNG(headImg, headImg, 80, 80,false);
                //头像变圆
                BufferedImage icon = ImageIO.read(new File(headImg));
                BufferedImage rounded = ChangeImage.makeRoundedCorner(icon, 180);
                ImageIO.write(rounded, "png", new File(headImg));

                Long times = System.currentTimeMillis();
                String saveFilePath = InviteDoImg.localPath+activityId+userOpenId+times.toString()+".jpg";

                //首先将二维码合并到活动图上 80. 600
                BufferedImage buffImg = InviteDoImg.watermark(new File(activityImg), new File(qrImg), qrIndex[0], qrIndex[1], 1.0f);
                InviteDoImg.generateWaterFile(buffImg, saveFilePath);

                //然后再将头像合并到活动图上200,600
                BufferedImage headImgbuffImg = InviteDoImg.watermark(new File(saveFilePath), new File(headImg), headImgIndex[0], headImgIndex[1], 1.0f);
                InviteDoImg.generateWaterFile(headImgbuffImg, saveFilePath);

                String waterMarkContent = "我是 "+wxUser.getNickName();
                log.info("waterMarkContent={}",waterMarkContent);
                //加名称水影
                InviteDoImg.addWaterMark(saveFilePath,saveFilePath,"我是 ", Color.getHSBColor(254,108,84),new Font("宋体",Font.PLAIN,13),userNameIndex);
                //208+35
                String olduserNameLeft = userNameIndex[0];
                userNameIndex[0] = "243";
                InviteDoImg.addWaterMark(saveFilePath,saveFilePath,wxUser.getNickName(), Color.getHSBColor(254,108,84),new Font("宋体",Font.PLAIN,15),userNameIndex);
//                InviteDoImg.addWaterMark(saveFilePath,saveFilePath,wxUser.getNickName(), Color.white,new Font("宋体",Font.PLAIN,15),userNameIndex);

                userNameIndex[0] = olduserNameLeft;
                String daiyan1 = userNameIndex[1];
                Integer newDaiyan1 = Integer.valueOf(daiyan1)+25;
                userNameIndex[1] = newDaiyan1.toString();
                InviteDoImg.addWaterMark(saveFilePath,saveFilePath,"我为"+wxActivity.getRemarks()+"代言", Color.BLACK,new Font("宋体",Font.PLAIN,17),userNameIndex);

                //上传图片到七牛云
                if(StringUtils.isNotEmpty(saveFilePath)){
                    File file = new File(saveFilePath);
                    String invitePicName = file.getName();
                    log.info("上传我的邀请合并图片file name:"+invitePicName);
                    try {
//                        String picUrl = QiniuUtils.upload(file, activityId+"|"+userOpenId+"|"+System.currentTimeMillis()+".jpg");
                        String picUrl = QiniuUtils.upload(file, activityId+userOpenId+times.toString()+".jpg");
                        log.info(picUrl);
                        jsonObject.put("inviteBannerPic",picUrl);

//                        jsonObject.put("inviteBannerPic",BusinessUtils.getImgFrontServer()+activityId+userOpenId+times.toString()+".jpg");

                        //保存数据库
                        WxUserInviteImg saveImg = new WxUserInviteImg();
                        saveImg.setUserOpenId(userOpenId);
                        saveImg.setActivityId(activityId);
//                        saveImg.setInviteImg(BusinessUtils.getImgFrontServer()+activityId+userOpenId+times.toString()+".jpg");
                        saveImg.setInviteImg(picUrl);
//                        saveImg.setInviteImg(picUrl);
                        saveImg.setRemarks("invite");
                        wxUserInviteImgService.save(saveImg);
                    } catch (Exception e) {
                        log.error("上传上传我的邀请合并图片file到七牛云失败={}",e.getMessage());
                        e.printStackTrace();
                    }
                }
            }

        return jsonObject;
    }

    /**
     * 邀请好友
     * @param activityId
     * @param userOpenId
     * @return
     */
    @RequestMapping("/inviteOld")
    public JSONObject inviteOld(String activityId,String userOpenId){
        JSONObject jsonObject = new JSONObject();

        WxUser wxUser = new WxUser();
        wxUser.setWxOpenId(userOpenId);
        List<WxUser> wxUserList = wxUserService.findList(wxUser);
        if(CollectionUtils.isNotEmpty(wxUserList)){

            WxUser result = wxUserList.get(0);
            jsonObject.put("userName",result.getNickName());
            jsonObject.put("headImg",result.getHeadImg());
//            if(StringUtils.isNotEmpty(result.getDisInvitePic())){
//                jsonObject.put("qrCodeUrl",result.getDisInvitePic());
//
//            }else{
                //二维码
                String url = BusinessUtils.getWxIndexFrontServer()+"?activityId="+activityId+"&inviteOpenId="+userOpenId;
                String qrCodeUrl = "";
                try {

                    String filePath = "/Users/qing/Desktop/";

                    String fileName = QRCodeUtils.encodeLocal(filePath,url);
                    String fileTemp = filePath+fileName;

                    String picUrl = "";

                    if(StringUtils.isNotEmpty(fileTemp)){

                        File file = new File(fileTemp);
                        String bannerPicName = file.getName();
                        log.info("upload groupPic file name:"+bannerPicName);
                        try {
                            picUrl = QiniuUtils.upload(file, bannerPicName);
                            log.info(picUrl);
                        } catch (QiniuException e) {
                            log.error("上传邀请二维码失败={}",e.getMessage());
                            e.printStackTrace();
                        }

                    }

//                    qrCodeUrl = QRCodeUtils.encode(url);
                    jsonObject.put("qrCodeUrl",picUrl);

                } catch (WriterException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                result.setDisInvitePic(qrCodeUrl);
                wxUserService.update(wxUser);

//            }

        }

        return jsonObject;
    }

    /**
     * 我的订单接口，
     * 后期添加的商家需要添加进去
     * @param activityId
     * @param userOpenId
     * @return
     */
    @RequestMapping("/myOrderNew")
    public JSONObject myOrderNew(String activityId,String userOpenId) {
        //最终返回结果
        JSONObject result = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        //先去查找是否购买了
        WxUserDisValueRecord wxUserDisValueRecord = new WxUserDisValueRecord();
        wxUserDisValueRecord.setBuyUserOpenId(userOpenId);
        wxUserDisValueRecord.setBuyActivityId(Long.valueOf(activityId));
        wxUserDisValueRecord.setBuyFlag(1);
        List<WxUserDisValueRecord> wxUserDisValueRecordList = wxUserDisValueRecordService.findList(wxUserDisValueRecord);
        //没购买直接返回
        if(CollectionUtil.isEmpty(wxUserDisValueRecordList)){
            return result;
        }

        //查询核销的时间
        WxActivity wxActivity = wxActivityService.get(activityId);
        result.put("afterBegin",DateUtils.formatDate(wxActivity.getAfterBeginTime()));
        result.put("afterEnd",DateUtils.formatDate(wxActivity.getAfterEndTime()));

        //这里需要兼容一下后面加入的商家也加入
        Map<String,String> mergeBusinessMap = wxUserActivityAfterService.mergeOrder(wxActivity);

        //查询购买订单
        WxUserActivityAfter wxUserActivityAfter = new WxUserActivityAfter();
        wxUserActivityAfter.setUserOpenId(userOpenId);
        wxUserActivityAfter.setActivityId(activityId);
        List<WxUserActivityAfter> wxUserActivityAfterList = wxUserActivityAfterService.findList(wxUserActivityAfter);
        if(CollectionUtil.isNotEmpty(wxUserActivityAfterList)){
            for(WxUserActivityAfter temp : wxUserActivityAfterList){
                JSONObject jsonObject = new JSONObject();

                String wxBusinessId = temp.getBusinessId();
                WxBusiness wxBusiness = wxBusinessService.get(wxBusinessId);
                String businessId = wxBusiness.getId();

                //包含就删除，最后map里剩下的就是订单后续添加的商家
                if(null != mergeBusinessMap && mergeBusinessMap.containsKey(businessId)){
                    jsonObject.put("businessId",businessId);
                    jsonObject.put("businessPhone",wxBusiness.getPhone());
                    jsonObject.put("businessName",wxBusiness.getName());
                    jsonObject.put("businessAddress",wxBusiness.getAddress());
                    jsonObject.put("businessRemarks",wxBusiness.getRemarks());
                    jsonObject.put("businessPic",wxBusiness.getPic());
                    jsonObject.put("after",temp.getAfter());
                    if(temp.getAfter() == 0){
                        jsonObject.put("afterStatus","核销");
                    }else{
                        jsonObject.put("afterStatus","已核销");
                    }
                    mergeBusinessMap.remove(businessId);
                    jsonArray.add(jsonObject);
                }
            }
        }

        if(null != mergeBusinessMap && mergeBusinessMap.size() > 0){
            for (Map.Entry<String,String> temp : mergeBusinessMap.entrySet()){
                //剩下的map,后续新添加的map,需要保存起来
                String businessId = temp.getKey();

                WxUser wxUser = wxUserService.findByOpenId(userOpenId);
                WxUserActivityAfter newAddActivityAfter = new WxUserActivityAfter();
                //订单号
                newAddActivityAfter.setOrderNum(wxActivity.getId()+wxUserActivityAfterList.size()+1);
                newAddActivityAfter.setActivityId(activityId);
                newAddActivityAfter.setBusinessId(businessId);
                newAddActivityAfter.setUserOpenId(userOpenId);
                newAddActivityAfter.setUserId(wxUser.getId());
                wxUserActivityAfterService.insert(newAddActivityAfter);

                //然后在插入到jsonArray中
                WxBusiness wxBusiness = wxBusinessService.get(businessId);
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("businessId",businessId);
                jsonObject.put("businessPhone",wxBusiness.getPhone());
                jsonObject.put("businessName",wxBusiness.getName());
                jsonObject.put("businessAddress",wxBusiness.getAddress());
                jsonObject.put("businessRemarks",wxBusiness.getRemarks());
                jsonObject.put("businessPic",wxBusiness.getPic());
                //未核销
                jsonObject.put("after","0");
                jsonObject.put("afterStatus","核销");
                jsonArray.add(jsonObject);
            }
        }

        result.put("data",jsonArray);
        return result;
    }

    /**
     * 我的订单接口，
     * 后期添加的商家需要添加进去
     * @param activityId
     * @param userOpenId
     * @return
     */
    @RequestMapping("/myOrder")
    public JSONArray muOrder(String activityId,String userOpenId){
        JSONArray jsonArray = new JSONArray();

        //先去查找是否购买了
        WxUserDisValueRecord wxUserDisValueRecord = new WxUserDisValueRecord();
        wxUserDisValueRecord.setBuyUserOpenId(userOpenId);
        wxUserDisValueRecord.setBuyActivityId(Long.valueOf(activityId));
        wxUserDisValueRecord.setBuyFlag(1);
        List<WxUserDisValueRecord> wxUserDisValueRecordList = wxUserDisValueRecordService.findList(wxUserDisValueRecord);
        //没购买直接返回
        if(CollectionUtil.isEmpty(wxUserDisValueRecordList)){
            return jsonArray;
        }

        //查找活动的的最新添加商家
        JSONObject result = new JSONObject();
        result.put("after",0);

        //查询活动是否过期了
        WxActivity wxActivity = wxActivityService.get(activityId);

        //兼容
        wxUserActivityAfterService.jianrong(wxActivity,activityId,userOpenId);

        Date endTime = wxActivity.getEndTime();
        //过期了
        if(new Date().after(endTime)){
            result.put("after",1);
        }

        WxUserActivityAfter wxUserActivityAfter = new WxUserActivityAfter();
        wxUserActivityAfter.setUserOpenId(userOpenId);
        wxUserActivityAfter.setActivityId(activityId);
        List<WxUserActivityAfter> wxUserActivityAfterList = wxUserActivityAfterService.findList(wxUserActivityAfter);
        log.info("size={}",wxUserActivityAfterList.size());
        if(CollectionUtils.isNotEmpty(wxUserActivityAfterList)){

            Map<String,List<WxUserActivityAfter>> map = new HashMap();

            for(WxUserActivityAfter te : wxUserActivityAfterList){
//
//                //查询用户的核销商家，和活动的商家进行比对，需要添加活动后续添加的商家
//                String businessId = te.getBusinessId();
//                if(allActivityBusinessList.contains(businessId)){
//                    //删除只剩下 核销里面没有查询出来的
//                    allActivityBusinessList.remove(businessId);
//                }

                String num = te.getOrderNum();
                if(map.containsKey(num)){
                    List<WxUserActivityAfter> list = map.get(num);
                    list.add(te);
                    continue;
                }

                List<WxUserActivityAfter> list = new LinkedList();
                list.add(te);
                map.put(num,list);

            }

            for(Map.Entry<String,List<WxUserActivityAfter>> m : map.entrySet()){
                JSONObject ob = new JSONObject();

                String num = m.getKey();
                ob.put("orderName",num);

                List<WxUserActivityAfter> value = m.getValue();
                JSONArray vArray = new JSONArray();
                for(WxUserActivityAfter v:value){

                    JSONObject jsonObject = new JSONObject();

                    jsonObject.put("after",v.getAfter());
                    //订单号
                    jsonObject.put("orderNum",v.getOrderNum());

                    String businessId = v.getBusinessId();
                    WxBusiness wxBusiness = wxBusinessService.get(businessId);
                    //商家名称
                    jsonObject.put("businessName",wxBusiness.getName());
                    //
                    jsonObject.put("businessId",wxBusiness.getId());
                    //商家头像
                    jsonObject.put("businessPic",wxBusiness.getPic());
                    //创建时间
                    jsonObject.put("createDate",v.getCreateDate());
                    ob.put("orderDate",v.getCreateDate());

                    vArray.add(jsonObject);
                }
                ob.put("orderValue",vArray);

                jsonArray.add(ob);
            }

        }

        result.put("dataArray",jsonArray);
        return jsonArray;
    }

    /**
     * 用户核销某个活动的中的某个商家
     * @param activityId
     * @param businessId
     * @param userOpenId
     * @return
     */
    @RequestMapping("/after")
    @Transactional(rollbackFor = Exception.class)
    public Integer after(String activityId,String businessId,String userOpenId,String orderNum,String miyao){

        //查询活动是否过期了
        WxActivity wxActivity = wxActivityService.get(activityId);
        //核销的过期时间
        Date endTime = wxActivity.getAfterEndTime();
        Date beginTime = wxActivity.getAfterBeginTime();
        //过期了
        if(new Date().after(endTime)){
            return -55;
        }
        //核销时间暂未开始
        if(beginTime.after(new Date())){
            return -33;
        }

        //校验秘要
        WxBusiness wxBusiness = wxBusinessService.get(businessId);
        if(StringUtil.isEmpty(wxBusiness.getHexiaoPassword())){
            //商家没密码没配置
            return -98;
        }

        if(StringUtil.isEmpty(miyao)){
            return -97;
        }

        //秘要不对
        if(!wxBusiness.getHexiaoPassword().equals(miyao)){
            return -96;
        }

        WxUserActivityAfter wxUserActivityAfter = new WxUserActivityAfter();
        wxUserActivityAfter.setActivityId(activityId);
        wxUserActivityAfter.setUserOpenId(userOpenId);
        wxUserActivityAfter.setBusinessId(businessId);
        //新版的订单不需要订单号，因为活动只能购买一次
//        wxUserActivityAfter.setOrderNum(orderNum);

        //下过单之后这个表里是都该活动的所有数据
        List<WxUserActivityAfter> wxUserActivityAfterList = wxUserActivityAfterService.findList(wxUserActivityAfter);
        log.info("核销查询的list={}",wxUserActivityAfterList);
        if(CollectionUtils.isNotEmpty(wxUserActivityAfterList)){

            WxUserActivityAfter findTemp = wxUserActivityAfterList.get(0);
            log.info("核销查询的单条数据={}",findTemp);
            Integer after = findTemp.getAfter();
            if(null != after ){

                //代表未核销
                if(after == 0){

                    findTemp.setAfter(1);
                    //核销总数+1
                    Integer afterCount = wxBusiness.getAfterCount();
                    if(null == afterCount){
                        afterCount = 0;
                    }
                    wxBusiness.setAfterCount(afterCount+1);
                    wxBusinessService.update(wxBusiness);

                    //更新用户核销状态
                    wxUserActivityAfterService.update(findTemp);

                    return 1;
                }else {
                    log.info("核销失败，该用户={},在活动={},商家={}已经核销过了",userOpenId,activityId,businessId);
                    return 99;
                }

            }

        }

        return 0;
    }


    public static void main(String[] args) throws Exception {



        String a ="https://image.lanstech.cn/b150a730-be58-4508-874e-ab61b55782d7.png";
        String b = "https://image.lanstech.cn/1052740099264176128.png";

        createLocalFile(a,"a");
        createLocalFile(b,"b");

        //输入图片地址
        String[] imgs={"/Users/qing/Desktop/a.jpg","/Users/qing/Desktop/b.jpg"};
        //调用方法生成图片
        merge(imgs,"jpg","/Users/qing/Desktop/test.jpg");

        System.out.println("111");
    }

    public static void createLocalFile(String path,String fileName) throws Exception {

        //new一个URL对象
        URL url = new URL(path);
        //打开链接
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        //设置请求方式为"GET"
        conn.setRequestMethod("GET");
        //超时响应时间为5秒
        conn.setConnectTimeout(5 * 1000);
        //通过输入流获取图片数据
        InputStream inStream = conn.getInputStream();
        //得到图片的二进制数据，以二进制封装得到数据，具有通用性
        byte[] data = readInputStream(inStream);
        //new一个文件对象用来保存图片，默认保存当前工程根目录
        File imageFile = new File("/Users/qing/Desktop/"+fileName+".jpg");
        //创建输出流
        FileOutputStream outStream = new FileOutputStream(imageFile);
        //写入数据
        outStream.write(data);
        //关闭输出流
        outStream.close();
    }


    public static byte[] readInputStream(InputStream inStream) throws Exception{
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        //创建一个Buffer字符串
        byte[] buffer = new byte[1024];
        //每次读取的字符串长度，如果为-1，代表全部读取完毕
        int len = 0;
        //使用一个输入流从buffer里把数据读取出来
        while( (len=inStream.read(buffer)) != -1 ){
            //用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
            outStream.write(buffer, 0, len);
        }
        //关闭输入流
        inStream.close();
        //把outStream里的数据写入内存
        return outStream.toByteArray();
    }


    public static Boolean merge(String[] imgs, String type, String dst_pic) {
            //获取需要拼接的图片长度
            int len = imgs.length;
            //判断长度是否大于0
            if (len < 1) {
                return false;
            }
            File[] src = new File[len];
            BufferedImage[] images = new BufferedImage[len];
            int[][] ImageArrays = new int[len][];
            for (int i = 0; i < len; i++) {
                try {
                    src[i] = new File(imgs[i]);
                    images[i] = ImageIO.read(src[i]);
                } catch (Exception e) {
                    e.printStackTrace();
                    return false;
                }
                int width = images[i].getWidth();
                int height = images[i].getHeight();
                // 从图片中读取RGB 像素
                ImageArrays[i] = new int[width * height];
                ImageArrays[i] = images[i].getRGB(0, 0, width, height,  ImageArrays[i], 0, width);
            }

            int dst_height = 0;
            int dst_width = images[0].getWidth();
            //合成图片像素
            for (int i = 0; i < images.length; i++) {
                dst_width = dst_width > images[i].getWidth() ? dst_width     : images[i].getWidth();
                dst_height += images[i].getHeight();
            }
            //合成后的图片
            System.out.println("宽度:"+dst_width);
            System.out.println("高度:"+dst_height);
            if (dst_height < 1) {
                System.out.println("dst_height < 1");
                return false;
            }
            // 生成新图片
            try {
                dst_width = images[0].getWidth();
                BufferedImage ImageNew = new BufferedImage(dst_width, dst_height,
                        BufferedImage.TYPE_INT_RGB);
                int height_i = 0;
                for (int i = 0; i < images.length; i++) {
                    ImageNew.setRGB(0, height_i, dst_width, images[i].getHeight(),
                            ImageArrays[i], 0, dst_width);
                    height_i += images[i].getHeight();
                }

                File outFile = new File(dst_pic);
                ImageIO.write(ImageNew, type, outFile);// 写图片 ，输出到硬盘
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
            return true;
        }


    @RequestMapping("/checkUserPay")
    public String checkUserPay(String activityId,String userOpnedId){

        WxUserDisValueRecord wxUserDisValueRecord = new WxUserDisValueRecord();
        wxUserDisValueRecord.setBuyActivityId(Long.valueOf(activityId));
        wxUserDisValueRecord.setBuyUserOpenId(userOpnedId);
        wxUserDisValueRecord.setBuyFlag(1);
        List<WxUserDisValueRecord> wxUserDisValueRecordList = wxUserDisValueRecordService.findList(wxUserDisValueRecord);
        if(CollectionUtil.isNotEmpty(wxUserDisValueRecordList)){
            return "1";
        }

        return "0";
    }
}
